package com.yzw.common.security;

import com.yzw.common.domain.EduAclPermission;
import com.yzw.common.domain.EduAclRole;
import com.yzw.common.service.EduAclPermissionService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @Author Yzw
 * @Description 查找访问当前url需要什么角色
 * @Date 2023/5/15 14:09
 * @Version 1.0
 */
@Component
public class UrlSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Resource
    EduAclPermissionService permissionService;
    AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        List<EduAclPermission> allMenus = permissionService.getAll();
        for (EduAclPermission menu : allMenus) {
            if (matcher.match(menu.getPermissionValue(), requestUrl)) {
                List<EduAclRole> roles = menu.getRoles();
                String[] roleCodes = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    roleCodes[i] = roles.get(i).getRoleCode();
                }
                return SecurityConfig.createList(roleCodes);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}